//
//  HNSH_AddressEditViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/2/26.
//

#import "HNSH_AddressEditViewController.h"

//view
#import "HNSH_AddressEditCell.h"
#import "HNSH_AddressEditChooseCell.h"
#import "HNSH_AddressEditFooterView.h"

#import "DLAddressPickerView.h"

@interface HNSH_AddressEditViewController ()
/** */
@property (nonatomic, strong)HNSH_AddressEditFooterView * footerView;
/**  */
@property (nonatomic, strong)UIButton * addBtn;
/** */
@property (nonatomic, copy)NSArray * dataArray;
/** */
@property (nonatomic, strong)HNSH_AddressModel * model;

@end

static NSString *HNSH_AddressEditCellID = @"HNSH_AddressEditCellID";
static NSString *HNSH_AddressEditChooseCellID = @"HNSH_AddressEditChooseCellID";

@implementation HNSH_AddressEditViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    
    [self showNavTitle:@"添加地址" showLeftItem:YES];
    
    [self configTableView];
    
    [self addAllViews];
        
    [self setDefaultData];
}

//MARK: Custom Methods
- (void)addAllViews{
    [self.view addSubview:self.addBtn];
}

//MARK: 默认配置
- (void)setDefaultData{
    NSString * address = [NSString stringWithFormat:@"%@%@%@", self.model.province_name ? : @"", self.model.city_name ? : @"", self.model.county_name ? : @""];
    self.dataArray = @[
        @{@"title":@"收货人：", @"place":@"请输入收货人姓名", @"con":self.model.name ? : @""},
        @{@"title":@"联系方式：", @"place":@"请输入手机号", @"con":self.model.phone ? : @""},
        @{@"title":@"所在地区：", @"place":@"选择地区", @"con":address ? : @""},
        @{@"title":@"详细地址：", @"place":@"街道、楼牌号", @"con":self.model.details ? : @""},
    ];
    [self.tableView reloadData];
}

- (void)textChangedWithTextField:(UITextField *)textField{
    HNSH_AddressEditCell * cell = (HNSH_AddressEditCell *)textField.superview.superview;
    NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row == 0) {
        self.model.name = textField.text;
    }
    if (indexPath.row == 1) {
        self.model.phone = textField.text;
    }
    if (indexPath.row == 3) {
        self.model.details = textField.text;
    }
}

//MARK: 保存
- (void)addBtnAction{
    [self.view endEditing:YES];
    //
    self.model.default_address = self.footerView.getDefaultStatus;
    //
    if (![self.model.name isNotBlank]) {
        [self.view makeToast:@"请输入收货人姓名"];
        return;
    }
    if (![self.model.phone isNotBlank]) {
        [self.view makeToast:@"请输入手机号"];
        return;
    }
    if (![NSString isValidateMobileWithPhone:self.model.phone]) {
        [self.view makeToast:@"请输入正确的手机号码"];
        return;
    }
    if (![self.model.province_name isNotBlank]) {
        [self.view makeToast:@"请选择所在地区"];
        return;
    }
    if (![self.model.details isNotBlank]) {
        [self.view makeToast:@"请输入详细地址"];;
        return;
    }
    if (self.addressModel) {
        [self updeteAddress];
    } else {
        [self createAddress];
    }
}

- (void)createAddress{
    NSDictionary * params = @{
        @"name":self.model.name,
        @"phone":self.model.phone,
        @"province_code":self.model.province_code,
        @"city_code":self.model.city_code,
        @"county_code":self.model.county_code,
        @"details":self.model.details,
        @"default_address":@(self.model.default_address),
    };
    [HNSH_ShopNetServer requestUserAddressCreateWithParams:params success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"添加成功"];
            //
            [self.navigationController popViewControllerAnimated:YES];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)updeteAddress{
    NSDictionary * params = @{
        @"id":self.addressModel.uid,
        @"name":self.model.name,
        @"phone":self.model.phone,
        @"province_code":self.model.province_code,
        @"city_code":self.model.city_code,
        @"county_code":self.model.county_code,
        @"details":self.model.details,
        @"default_address":@(self.model.default_address),
    };
    [HNSH_ShopNetServer requestUserAddressUpdateWithParams:params success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self.view makeToast:@"更细成功"];
            //
            [self.navigationController popViewControllerAnimated:YES];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: Setter Methods
- (void)setAddressModel:(HNSH_AddressModel *)addressModel{
    _addressModel = addressModel;
    
    self.model = addressModel;
}

//MARK: Getter Methods
- (HNSH_AddressEditFooterView *)footerView{
    if (!_footerView) {
        _footerView = [[HNSH_AddressEditFooterView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10 + 80)];
        _footerView.isDefault = self.model.default_address;
    }
    return _footerView;
}

- (UIButton *)addBtn{
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addBtn.frame = CGRectMake(30, kScreenHeight - 50 - 23 - kBottomSafeHeight, kScreenWidth - 60, 50);
        [_addBtn setTitle:@"保存并使用" forState:UIControlStateNormal];
        [_addBtn setTitleColor:[UIColor appWhiteLabelColor] forState:UIControlStateNormal];
        _addBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        _addBtn.backgroundColor = [UIColor appGreenColor];
        _addBtn.layer.cornerRadius = 25;
        _addBtn.layer.masksToBounds = YES;
        [_addBtn addTarget:self action:@selector(addBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

- (HNSH_AddressModel *)model{
    if (!_model) {
        _model = [HNSH_AddressModel new];
    }
    return _model;
}

- (void)configTableView {
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(kNavBarAndStatusBarHeight, 0, 50 + 12 + kBottomSafeHeight, 0));
    }];
    [self.tableView registerClass:[HNSH_AddressEditCell class] forCellReuseIdentifier:HNSH_AddressEditCellID];
    [self.tableView registerClass:[HNSH_AddressEditChooseCell class] forCellReuseIdentifier:HNSH_AddressEditChooseCellID];
    self.tableView.tableFooterView = self.footerView;
}

//MARK: UITableViewDelegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        HNSH_AddressEditChooseCell * cell = [tableView dequeueReusableCellWithIdentifier:HNSH_AddressEditChooseCellID];
        cell.dic = self.dataArray[indexPath.row];
        return cell;
    } else {
        HNSH_AddressEditCell * cell = [tableView dequeueReusableCellWithIdentifier:HNSH_AddressEditCellID];
        cell.dic = self.dataArray[indexPath.row];
        WeakSelf(weakSelf);
        cell.textChangedBlock = ^(UITextField * _Nonnull textField) {
            [weakSelf textChangedWithTextField:textField];
        };
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        [self chooseAddress];
    }
}

//MARK: 选择地区
- (void)chooseAddress{
    [self.view endEditing:YES];
    //
    [DLAddressPickerView showAddressPickerViewWithMaxCom:3 block:^(NSArray * _Nonnull addressArray) {
        [addressArray enumerateObjectsUsingBlock:^(DLAddressModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx == 0) {
                self.model.province_code = obj.code;
                self.model.province_name = obj.name;
            }
            if (idx == 1) {
                self.model.city_code = obj.code;
                self.model.city_name = obj.name;
            }
            if (idx == 2) {
                self.model.county_code = obj.code;
                self.model.county_name = obj.name;
            }
        }];
        [self setDefaultData];
    }];
}


@end
